<template>
    <div class="login">
        <div class="moduleHead">
            <router-link :to="{ name: 'home' }">
                <span class="back"></span>
            </router-link>
            <span> {{language.login_title}} </span>
        </div>
        <div class="body">
            <div v-bind:class="username.length > 0 ? 'formrow mt30 hasValue' : 'formrow mt30'">
                <input spellcheck="false" autocapitalize="off" autocorrect="off" autocomplete="off" id="userName" name="userName" type="text" @focus="focusInput" @input="updateInput" @blur="blurInput" v-validate="'required|usernameORemail'" :value="username" />
                <label :class="{'validate-error-color': hasValidateError('userName')}" for="userName">{{userNameLabel}}</label>
                <span v-show="showClearBtn == 'userName'" @touchstart="clearUsername" class="cleanIco"></span>
            </div>
            <div v-bind:class="password.length > 0 ? 'formrow hasValue' : 'formrow'">
                <input v-on:keyup.13="login" maxlength=20 spellcheck="false" autocapitalize="off" autocorrect="off" autocomplete="new-password" name="passWord" type="password" id="passWord" @focus="focusInput" @input="updateInput" @blur="blurInput" v-validate="'required|min|max'" :value="password" />
                <label for="passWord" :class="{'validate-error-color': hasValidateError('passWord')}">{{passWordLabel}}</label>
                <span v-show="showClearBtn == 'passWord'" @touchstart="clearPassword " class="cleanIco"></span>
            </div>
            <div v-show="showNumber" v-bind:class="confirmNumber.length == 0 ? 'formrow' : 'formrow hasValue'">
                <input v-on:keyup.13="login" maxlength=6 spellcheck="false" autocapitalize="off" autocorrect="off" autocomplete="off" name="confirmNumber" id="confirmNumber" type="text" @focus="focusInput" @input="updateInput" @blur="blurInput" v-validate:lazy="'required'" class='confirm_number_input' :value="confirmNumber" />
                <label for="confirmNumber" :class="{'validate-error-color': hasValidateError('confirmNumber')}">{{confirmNumberLabel}}</label>
                <div class='verify_img_box' :class="{verifyImgShow:!verifyImgLoad}">
                    <img @click='loadConfirmNumber' :src='numUrl'></img>
                </div>
            </div>
            <div class="forget_pswd ">
                <router-link :to="{ name: 'forgotPassword' } ">
                    {{language.login_forgot_password}}
                </router-link>
            </div>
            <div class="formrow ">
                <button type="button" class="btn" @click="login" :class="btnClass">
                    <loading :props="{show:loading,type:'btn'}"></loading>
                    {{language.login_title}}
                </button>
            </div>
            <div class="feedback">
                <router-link :to="{ name: 'feedback' } ">
                    <span> {{language.login_feedback}} </span>
                </router-link>
            </div>
        </div>
    </div>
</template>
<script>
import validationMixin from '../plugins/my-validate'
import permissionPartMixin from '../common/permissionPartMixin'
import loading from './Loading'

export default {

    name: 'login',

    mixins: [validationMixin, permissionPartMixin],

    components: {
        loading,
    },

    data: function() {
        return {
            username: '',
            password: '',
            confirmNumber: '',
            showNumber: false, //是否显示验证码
            loading: false, //登陆laoding
            apiCallbackError: false, //判断是否是API返回错误，需要特殊处理 eg:username or passowrd
            numUrl: '', //验证码url
            verifyImgLoad: false,
            checkAllOK: false, //登陆按钮可用状态  
            showClearBtn: '',
            userNameLabel: '',
            passWordLabel: '',
            confirmNumberLabel: '',
        }
    },

    created() {
        this.userNameLabel = this.language.login_userNameLabel;
        this.passWordLabel = this.language.login_passWordLabel;
        this.confirmNumberLabel = this.language.login_confirmNumberLabel;
    },

    activated() {
        this.password = '';
        this.syncLogin();
    },

    computed: {
        btnClass: function() {
            let activeClass = 'btnFail';
            if (this.checkAllOK) {
                activeClass = 'btnOK'
            } else {
                activeClass = 'btnFail'
            }
            return activeClass;
        }
    },

    methods: {

        clearUsername: function() {
            this.username = '';
            this.clearElNameValue('userName');
        },

        clearPassword: function() {
            this.password = '';
            this.clearElNameValue('passWord');
        },

        clearConfirmNumber: function() {
            this.confirmNumber = '';
            this.clearElNameValue('confirmNumber');
        },

        setAllInput: function() {
            var obj = {
                errorCode: 1,
                errormsg: '',
            };
            this.changeCacheFields('userName', obj);
            this.changeCacheFields('passWord', obj);
            this.changeCacheFields('confirmNumber', obj);
            this.userNameLabel = this.language.login_userNameLabel;
            this.passWordLabel = this.language.login_passWordLabel;
            this.confirmNumberLabel = this.language.login_confirmNumberLabel;
        },

        checkShowClearBtn: function(e) {
            if (e.target.value) {
                this.showClearBtn = e.target.name;
            } else {
                this.showClearBtn = '';
            }
        },

        setShowError: function(val) {
            this.changeField('userName', 'showError', val);
            this.changeField('passWord', 'showError', val);
            this.changeField('confirmNumber', 'showError', val);
        },

        focusInput(e) {
            this.setShowError(false);
            this.checkShowClearBtn(e);
            if (this.apiCallbackError) {
                this.setAllInput();
                this.apiCallbackError = false;
                this.$forceUpdate();
            }
        },

        updateInput(e) {
            this.checkShowClearBtn(e);
            let name = e.target.name,
                value = e.target.value;
            if (name == 'userName') {
                this.username = value;
            } else if (name == 'passWord') {
                this.password = value;
            } else if (name == 'confirmNumber') {
                this.confirmNumber = value;
            }
            this.updateBtn(name);
        },

        blurInput(e) {
            let name = e.target.name,
                value = e.target.value;
            this.showClearBtn = '';

            if (value == '') {
                this.changeCacheFields(name, {
                    errorCode: 0,
                    errormsg: '',
                });
            }
            this[name + 'Label'] = this.hasValidateError(name) ? this.getValidateError(name) : this.language['login_' + name + 'Label'];
        },

        updateBtn(name) {
            //console.log('updateBtn', this.getCacheFields());
            if (this.checkOneAll(name)) {
                this.checkAllOK = true;
            } else {
                this.checkAllOK = false;
            }
            this[name + 'Label'] = this.hasValidateError(name) ? this.getValidateError(name) : this.language['login_' + name + 'Label'];
        },

        login: function() {
            this.setShowError(true);
            if (this.checkAllOK && this.checkAll() && !this.loading) {
                this.$store.dispatch('user_login', this);
                this.loading = true;
            }
            this.$forceUpdate();
        },

        loadConfirmNumber: function() {
            var tthis = this,
                newImg = new Image(),
                verifyUrl = Config.API_URL + 'show_captcha_url?username=' + this.username + '&r=' + Math.random();

            tthis.verifyImgLoad = true;
            tthis.numUrl = verifyUrl;
            newImg.onload = function() {
                tthis.verifyImgLoad = false;
            };
            newImg.src = verifyUrl;
        },

        changeNumberState: function() {
            let tthis = this;
            this.checkAllOK = false;
            this.loadConfirmNumber();
            //pit on iphone6
            setTimeout(function() {
                tthis.showNumber = true;
            }, 500);
            this.changeField('confirmNumber', 'need', true);
        },

        loginCallback: function(data) {
            if (typeof(data.errcode) == 'undefined') {
                this.successHandler(data);
            } else {
                this.errorsHandler(data);
            }
        },

        successHandler: function(data) {
            this.permissionPartMixin_LoginSuccessful(data);
        },

        errorsHandler: function(data) {
            this.apiCallbackError = true;
            //逻辑判断后，调用修改验证对象
            if (data.errcode == 1002) {
                this.$router.push({
                    name: 'activateAccount',
                    query: {
                        userName: this.username
                    }
                })
            } else if (data.errcode == 108) {
                //this.password = '';
                //this.username = '';
                var obj = {
                    errorCode: 2, //0是初始化 1是通过， 2是错误
                    errormsg: data.errmsg, //错误文本
                };
                //this.changeCacheFields('passWord', obj);
                this.changeCacheFields('userName', obj);
                //this.passWordLabel = data.errmsg;
                this.userNameLabel = data.errmsg;
                this.changeNumberState();
            } else if (data.errcode == 107) {
                this.$router.push({
                    name: 'activateAccount',
                    query: {
                        userName: this.username
                    }
                })
            } else if (data.errcode == 109) {
                this.$router.push({
                    name: 'resetPassword'
                })
            } else if (parseInt(data.errcode) == 103 || parseInt(data.errcode) == 110) {
                this.changeNumberState();
            } else if (parseInt(data.errcode) == 102) {
                var obj = {
                    errorCode: 2, //0是初始化 1是通过， 2是错误
                    errormsg: data.errmsg, //错误文本
                };
                this.changeCacheFields('confirmNumber', obj);
                this.confirmNumberLabel = data.errmsg;
                this.changeNumberState();
                //this.clearConfirmNumber();
            } else {
                var objUserName = {
                        errorCode: 2, //0是初始化 1是通过， 2是错误
                        errormsg: data.errmsg, //错误文本
                    },
                    objPassWord = {
                        errorCode: 2, //0是初始化 1是通过， 2是错误
                        errormsg: data.errmsg, //错误文本
                    };
                this.changeCacheFields('userName', objUserName);
                //this.changeCacheFields('passWord', objPassWord);
                this.userNameLabel = data.errmsg;
                //this.passWordLabel = data.errmsg;
            }
        }
    }
}

</script>
<style scoped>
.login {
    padding-top: 44px;
}

.login .body {
    padding: 0 20px 0;
}

.login .formrow {
    margin-top: 20px;
    position: relative;
    min-height: 46px;
}

.login .formrow label {
    position: absolute;
    left: 0;
    top: 10px;
    min-height: 16px;
    width: 100%;
    line-height: 16px;
    z-index: 1;
    color: #757575;
    font-size: 14px;
    -webkit-transition: all .2s;
    transition: all .2s;
    padding: 5px 0;
}

.login .formrow input {
    border: 0;
    border-bottom: 1px solid #ccc;
    width: 100%;
    color: #333;
    height: 46px;
    line-height: 20px;
    padding: 15px 0 0 0;
    box-sizing: border-box;
    font-size: 14px;
    font-family: Helvetica, Tahoma, Arial, 华文细黑, 微软雅黑, sans-serif;
    position: relative;
    border-radius: 0;
}

.login .hasValue label,
.login .hasValue input:focus~label,
.login .formrow input:focus~label {
    transform: scale(.8, .8) translate(-12.5%, -15px);
    -moz-transform: scale(.8, .8) translate(-12.5%, -15px);
    -webkit-transform: scale(.8, .8) translate(-12.5%, -15px);
    color: #222;
    top: inherit;
    bottom: 10px;
}

.login .formrow input.validate-error-border~label {
    color: #f00;
}

.cleanIco:nth-last-child(2) {
    font-size: 11px;
    top: -10px;
}

.login .formrow .confirm_number_input {
    width: calc(100% - 110px);
    float: left;
}

.login .formrow .verify_img_box {
    height: 46px;
    float: right;
    width: 106px;
    background: url(./../assets/max_loading.gif) center no-repeat;
    background-size: 15px auto;
    box-shadow: 0 0 1px #333 inset;
    background-color: #fff;
    border-radius: 3px;
}

.login .formrow .verify_img_box img {
    width: 100%;
    height: 100%;
    display: none;
}

.login .formrow .verify_img_box.verifyImgShow img {
    background-color: #fff;
    display: block;
}

.login .btnFail {
    opacity: .6;
}

.login .btnOK {
}

.login .cleanIco {
    position: absolute;
    right: 2px;
    top: 17px;
    width: 25px;
    height: 25px;
    cursor: pointer;
    background: url(./../assets/icoClose.png) center no-repeat;
    background-size: 16px auto;
}

.login .forget_pswd {
    text-align: right;
    font-size: 14px;
    cursor: pointer;
    color: #999;
    padding: 20px 0 0 0;
}

.login .mt30 {
    margin-top: 30px;
}

.login .feedback {
    position: absolute;
    bottom: 20px;
    left: 0;
    width: 100%;
    text-align: center;
    font-size: 14px;
    color: #666;
}

@media screen and (orientation:landscape) {
    .login .feedback {
        position: relative;
        top: 0;
        left: 0;
        margin-top: 50px;
        margin-bottom: 30px;
    }
}

</style>
